package com.wuwei.elearning.utils;

import org.jodconverter.core.DocumentConverter;
import org.jodconverter.core.office.OfficeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;

@Service
public class DocumentService {

    @Autowired
    private DocumentConverter documentConverter;

    public void convertToPdf(File inputFile, File outputFile) throws OfficeException {
        documentConverter.convert(inputFile)
                .to(outputFile)
                .execute();
    }

    public void convertStreamToPdf(InputStream inputStream, File outputFile) throws OfficeException {
        documentConverter.convert(inputStream)
                .to(outputFile)
                .execute();
    }

    public void convertStreamToPdf(InputStream inputStream, OutputStream outputStream) throws OfficeException, IOException {
        // 创建临时文件
        File inputFile = File.createTempFile("input-", ".docx");
        File outputFile = File.createTempFile("output-", ".pdf");

        try {
            // 将输入流写入临时文件
            try (FileOutputStream fos = new FileOutputStream(inputFile)) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) > 0) {
                    fos.write(buffer, 0, length);
                }
            }

            // 执行转换
            documentConverter.convert(inputFile)
                    .to(outputFile)
                    .execute();

            // 将结果写入输出流
            try (FileInputStream fis = new FileInputStream(outputFile)) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
            }
        } finally {
            // 删除临时文件
            inputFile.delete();
            outputFile.delete();
        }
    }
}